package com.ldcc.report_system.ui.report;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.ldcc.report_system.ApplicationConfig;
import com.ldcc.report_system.ReportApplication;
import com.ldcc.report_system.api.param.WeekReportParam;
import com.ldcc.report_system.api.results.WeekReportResult;
import com.ldcc.report_system.databinding.ActivityAddWeekReportBinding;
import com.ldcc.report_system.listener.SoftKeyBoardListener;
import com.ldcc.report_system.util.ActivitySkipUtil;
import com.ldcc.report_system.util.AlertUtil;
import com.ldcc.report_system.util.KeyBroadUtils;
import com.ldcc.report_system.util.LoadingUtil;
import com.ldcc.report_system.util.ServerDateUtils;
import com.ldcc.report_system.util.WindowUtils;
import com.ldcc.report_system.util.http.ClientRequestManage;
import com.ldcc.report_system.util.http.HttpObserver;
import com.ldcc.report_system.util.http.ServerResponse;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author wwj[yeshengkele@outlook.com]
 * @description 添加周报界面
 */
public class AddWeekReportActivity extends AppCompatActivity {
    public static final String TAG = "AddWeekReportActivity";
    private ActivityAddWeekReportBinding addWeekReportBinding;
    // 主界面原始高度
    private int addReportHeight;

    // 添加标识
    public static final int ADD_FLAG = 0;
    // 查看标识
    public static final int SHOW_FLAG = 1;
    // 修改标识
    public static final int UPDATE_FLAG = 2;

    // 界面操作标识, 默认添加操作
    private int operationFlag = AddWeekReportActivity.ADD_FLAG;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.addWeekReportBinding = ActivityAddWeekReportBinding.inflate(getLayoutInflater());
        setContentView(this.addWeekReportBinding.getRoot());
        // 设置界面顶部为透明
        WindowUtils.setWindowTopTransparent(getWindow());
        this.initPage();
    }


    /**
     * @description 初始化界面
     */
    private void initPage() {
        // 看日志
        this.addWeekReportBinding.commitReportBottomBtn.showReportBtn.setOnClickListener(view ->
                ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.SHOW_REPORT_FRAGMENT));
        // 写日志
        this.addWeekReportBinding.commitReportBottomBtn.addReportBtn.setOnClickListener(view ->
                ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.ADD_REPORT_FRAGMENT));
        // 提交日志
        this.addWeekReportBinding.commitReportBottomBtn.commitReportBtn.setOnClickListener(view -> {
            addWeekReport();
        });
        // 禁用日期选择控件事件
        this.addWeekReportBinding.datePickerBtn.setEnabled(false);

        String dataId = getIntent().getStringExtra(ActivitySkipUtil.DATA_ID);
        // 判断 dataId 是否为空，为空则是添加操作，不为空则是查看或修改操作
        if (dataId != null) {
            // 数据id不为空，查看或者编辑操作
            this.getDayReport(dataId);
            if (getIntent().getBooleanExtra(ActivitySkipUtil.DATA_EDIT_FLAG, false)) {
                this.operationFlag = AddWeekReportActivity.UPDATE_FLAG;
                setWeekReportEvent();
                // 提交日志
                this.addWeekReportBinding.commitReportBottomBtn.commitReportBtn.setOnClickListener(view -> {
                    updateWeekReport(dataId);
                });
            }else {
                // 查看操作
                this.operationFlag = AddWeekReportActivity.SHOW_FLAG;
                setActivityEnable(false);
                // 隐藏提交按钮
                addWeekReportBinding.commitReportBottomBtn.commitReportLayout.setVisibility(View.GONE);
            }
        }else {
            // dataId 为空，则为添加操作
            this.operationFlag = AddDayReportActivity.ADD_FLAG;
            setWeekReportEvent();
            // 提交周报
            this.addWeekReportBinding.commitReportBottomBtn.commitReportBtn.setOnClickListener(view -> {
                addWeekReport();
            });
        }


        // 监听键盘事件
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height, int visibleHeight) {
                //  这里才会有高度
                addReportHeight = addWeekReportBinding.addReportMainView.getHeight();
                Log.e(TAG, "keyBoardShow: 获取当前高度：" + addReportHeight);
                addWeekReportBinding.addReportMainView.setLayoutParams(
                        new LinearLayout.LayoutParams(addWeekReportBinding.addReportMainView.getWidth(), addReportHeight - height));
            }

            @Override
            public void keyBoardHide(int height, int visibleHeight) {
                addWeekReportBinding.addReportMainView.setLayoutParams(
                        new LinearLayout.LayoutParams(addWeekReportBinding.addReportMainView.getWidth(), addReportHeight));
            }
        });
    }

    /**
     * 查询周报信息并把信息显示在界面
     * @param dataId 周报id
     */
    private void getDayReport(String dataId) {
        ClientRequestManage.getInstance().getWeekReportApi().getById(dataId).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<WeekReportResult>(ReportApplication.getContext(), null) {

                    @Override
                    public void onSuccess(ServerResponse<WeekReportResult> response_entity) {
                        WeekReportResult data = response_entity.getData();
                        String gmtCreate = data.getGmtCreate();

                        // 设置日期
                        addWeekReportBinding.datePickerBtn.setDate(
                                ServerDateUtils.getDateYear(gmtCreate),
                                ServerDateUtils.getDateMonth(gmtCreate),
                                ServerDateUtils.getDateDay(gmtCreate)
                        );
                        // 设置值
                        addWeekReportBinding.finish.getEditValue().setText(data.getFinish());
                        addWeekReportBinding.nextWeekPlan.getEditValue().setText(data.getNextWeekPlan());
                        addWeekReportBinding.beContinued.getEditValue().setText(data.getBeContinued());
                        addWeekReportBinding.remarks.getEditValue().setText(data.getRemarks());
                    }
                });
    }

    /**
     * @description 禁用界面上所有输入组件
     */
    private void setActivityEnable(boolean enable) {
        addWeekReportBinding.finish.getEditValue().setEnabled(enable);
        addWeekReportBinding.nextWeekPlan.getEditValue().setEnabled(enable);
        addWeekReportBinding.beContinued.getEditValue().setEnabled(enable);
        addWeekReportBinding.remarks.getEditValue().setEnabled(enable);
    }

    private void setWeekReportEvent() {
        // 监听键盘事件
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height, int visibleHeight) {
                // 在这里才会有高度
                addReportHeight = addWeekReportBinding.addReportMainView.getHeight();
                Log.e(TAG, "keyBoardShow: 获取当前高度" + addReportHeight);
                addWeekReportBinding.addReportMainView.setLayoutParams(
                        new LinearLayout.LayoutParams(addWeekReportBinding.addReportMainView.getWidth(), addReportHeight - height));
            }

            @Override
            public void keyBoardHide(int height, int visibleHeight) {
                addWeekReportBinding.addReportMainView.setLayoutParams(
                        new LinearLayout.LayoutParams(addWeekReportBinding.addReportMainView.getWidth(), addReportHeight));
            }
        });
    }

    /**
     * 修改周报
     * @param id 周报 id
     */
    private void updateWeekReport(String id) {
        // 完成的工作
        String finish = this.addWeekReportBinding.finish.getEditValue().getText().toString();
        // 未完成
        String beContinued = this.addWeekReportBinding.beContinued.getEditValue().getText().toString();
        // 下周计划
        String nextWeekPlan = this.addWeekReportBinding.nextWeekPlan.getEditValue().getText().toString();
        // 备注信息
        String remarks = this.addWeekReportBinding.remarks.getEditValue().getText().toString();

        ClientRequestManage.getInstance().getWeekReportApi().update(new WeekReportParam() {{
            setId(id);
            setFinish(finish);
            setBeContinued(beContinued);
            setNextWeekPlan(nextWeekPlan);
            setRemarks(remarks);
        }}).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<Object>(ReportApplication.getContext(), null) {

                    @Override
                    public void onSuccess(ServerResponse<Object> response_entity) {
                        AlertUtil.shortTime("修改成功");
                        KeyBroadUtils.hideKeyboard(ReportApplication.getContext(), getWindow().getDecorView().getWindowToken());
                    }
                });
    }

    private void addWeekReport() {
        // 完成的工作
        String finish = this.addWeekReportBinding.finish.getEditValue().getText().toString();
        // 未完成
        String beContinued = this.addWeekReportBinding.beContinued.getEditValue().getText().toString();
        // 下周计划
        String nextWeekPlan = this.addWeekReportBinding.nextWeekPlan.getEditValue().getText().toString();
        // 备注信息
        String remarks = this.addWeekReportBinding.remarks.getEditValue().getText().toString();
        Log.e(TAG, "finish: " + finish);
        Log.e(TAG, "beContinued: " + beContinued);
        Log.e(TAG, "nextWeekPlan: " + nextWeekPlan);
        Log.e(TAG, "remarks: " + remarks);
        ClientRequestManage.getInstance().getWeekReportApi().save(new WeekReportParam() {{
            setFinish(finish);
            setBeContinued(beContinued);
            setNextWeekPlan(nextWeekPlan);
            setRemarks(remarks);
        }}).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<Object>(ReportApplication.getContext(), LoadingUtil.dialogLoadingOpen("请稍后", "正在连接服务器....", this)) {
                    @Override
                    public void onSuccess(ServerResponse<Object> response_entity) {
                        // 不带参数跳转页面
                        ActivitySkipUtil.backMainActivityFragment(AddWeekReportActivity.this, ApplicationConfig.SHOW_REPORT_FRAGMENT);
                    }
                });
    }


    /**
     * @description 返回键事件, 返回, 选择日报界面
     */
    @Override
    public void onBackPressed() {
        if(isAdd()) {
            ActivitySkipUtil.backMainActivityFragment(this, ApplicationConfig.ADD_REPORT_FRAGMENT);
        }else {
            ActivitySkipUtil.backMainActivityFragment(this,ApplicationConfig.SHOW_REPORT_FRAGMENT);
        }

    }

    /**
     * @return 是否为添加操作
     */
    public boolean isAdd() {
        return this.operationFlag == AddWeekReportActivity.ADD_FLAG;
    }

    /**
     * @return 是否为修改操作
     */
    public boolean isUpdate() {
        return this.operationFlag == AddDayReportActivity.UPDATE_FLAG;
    }

    /**
     * @return 是否为查看操作
     */
    public boolean isShow() {
        return this.operationFlag == AddDayReportActivity.SHOW_FLAG;
    }

}